package 并发编程18.自旋锁;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 可重入的自旋锁
 *
 * @author idea
 * @data 2019/2/19
 */
public class ReInSpinLock {

    private AtomicReference<Thread> cas;

    private int count;

    public void lock() {
        Thread thread = Thread.currentThread();

        if (thread == cas.get()) {
            count++;
            return;
        }
        while (!cas.compareAndSet(null, thread)) {

        }
    }


    public void unlock() {
        Thread cur = Thread.currentThread();
        if (cur == cas.get()) {
            if (count > 0) {
                count--;
            } else {
                //保证获取锁和释放锁的次数都是相同的
                cas.compareAndSet(cur, null);
            }
        }
    }
}
